<?php
use think\Db;

/**
 * 正确提示
 * @author rocky
 * @return mixed
 */
if (!function_exists('jsuccess')) {
    function jsuccess($data, $msg = '', $url = '')
    {
        $res['code'] = 1;
        $res['msg'] = $msg ? $msg : '操作成功';
        $res['data'] = $data;
        $res['url'] = $url;

        header('Content-Type:text/html; charset=utf-8');
        exit(json_encode($res));
    }
}

/**
 * 错误提示
 * @author rocky
 * @return mixed
 */
if (!function_exists('jerror')) {
    function jerror($msg, $url = '', $data='')
    {
        $res['code'] = 0;
        $res['msg'] = $msg ? $msg : '操作失败';
        $res['url'] = $url;
        $res['data'] = $data;

        header('Content-Type:text/html; charset=utf-8');
        exit(json_encode($res));
    }
}

/**
 * HTTP Protocol defined status codes
 * HTTP协议状态码,调用函数时候只需要将$num赋予一个下表中的已知值就直接会返回状态了。
 * @param int $num
 */
if (!function_exists('headError')) {
    function headError($num) {
        $http = array (
            100 => "HTTP/1.1 100 Continue",
            101 => "HTTP/1.1 101 Switching Protocols",
            200 => "HTTP/1.1 200 OK",
            201 => "HTTP/1.1 201 Created",
            202 => "HTTP/1.1 202 Accepted",
            203 => "HTTP/1.1 203 Non-Authoritative Information",
            204 => "HTTP/1.1 204 No Content",
            205 => "HTTP/1.1 205 Reset Content",
            206 => "HTTP/1.1 206 Partial Content",
            300 => "HTTP/1.1 300 Multiple Choices",
            301 => "HTTP/1.1 301 Moved Permanently",
            302 => "HTTP/1.1 302 Found",
            303 => "HTTP/1.1 303 See Other",
            304 => "HTTP/1.1 304 Not Modified",
            305 => "HTTP/1.1 305 Use Proxy",
            307 => "HTTP/1.1 307 Temporary Redirect",
            400 => "HTTP/1.1 400 Bad Request",
            401 => "HTTP/1.1 401 Unauthorized",
            402 => "HTTP/1.1 402 Payment Required",
            403 => "HTTP/1.1 403 Forbidden",
            404 => "HTTP/1.1 404 Not Found",
            405 => "HTTP/1.1 405 Method Not Allowed",
            406 => "HTTP/1.1 406 Not Acceptable",
            407 => "HTTP/1.1 407 Proxy Authentication Required",
            408 => "HTTP/1.1 408 Request Time-out",
            409 => "HTTP/1.1 409 Conflict",
            410 => "HTTP/1.1 410 Gone",
            411 => "HTTP/1.1 411 Length Required",
            412 => "HTTP/1.1 412 Precondition Failed",
            413 => "HTTP/1.1 413 Request Entity Too Large",
            414 => "HTTP/1.1 414 Request-URI Too Large",
            415 => "HTTP/1.1 415 Unsupported Media Type",
            416 => "HTTP/1.1 416 Requested range not satisfiable",
            417 => "HTTP/1.1 417 Expectation Failed",
            500 => "HTTP/1.1 500 Internal Server Error",
            501 => "HTTP/1.1 501 Not Implemented",
            502 => "HTTP/1.1 502 Bad Gateway",
            503 => "HTTP/1.1 503 Service Unavailable",
            504 => "HTTP/1.1 504 Gateway Time-out",

            505 => "HTTP/1.1 505 Votes Exceeded"
        );
        header($http[$num]);
    }
}

if (!function_exists('value2key')) {
    function value2key($array){
        $new = [];
        foreach($array as $k=>$v){
            $new[$v] = $v;
        }
        return $new;
    }
}

if (!function_exists('v')) {

    /**
     * 打印页面变量
     * @param string $value 变量值
     * @author rocky
     * @return string
     */
    function v($value = '', $exist = 1)
    {
        echo "<pre>";
        print_r($value);
        echo "</pre>";
        if($exist) exit;
    }
}

if (!function_exists('vlastsql')) {
    function vlastsql(){
        v(db::getlastsql());
    }
}

if (!function_exists('is_mobile')) {
    function is_mobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }
}

if (!function_exists('is_weixin')) {
    function is_weixin(){
        if ( isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return;
    }
}

if (!function_exists('is_kcz')) {
    function is_kcz(){
        if ( isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'kanchangzhou') !== false ) {
            return true;
        }
        return;
    }
}

if (!function_exists('micro_time')) {
    function micro_time(){
        return time()*1000;
    }
}

if (!function_exists('time_tran')) {
    /**
     * 转换时间
     * @param int $timer 时间戳
     * @author rocky <jy00730190@qq.com>
     * @return string
     */
    function time_tran($timer)
    {
        $diff = $_SERVER['REQUEST_TIME'] - $timer;
        $day  = floor($diff / 86400);
        $free = $diff % 86400;
        if ($day > 0) {
            return $day . " 天前";
        } else {
            if ($free > 0) {
                $hour = floor($free / 3600);
                $free = $free % 3600;
                if ($hour > 0) {
                    return $hour . " 小时前";
                } else {
                    if ($free > 0) {
                        $min = floor($free / 60);
                        $free = $free % 60;
                        if ($min > 0) {
                            return $min . " 分钟前";
                        } else {
                            if ($free > 0) {
                                return $free . " 秒前";
                            } else {
                                return '刚刚';
                            }
                        }
                    } else {
                        return '刚刚';
                    }
                }
            } else {
                return '刚刚';
            }
        }
    }
}

if (!function_exists('table_exist')) {
    /**
     * 检查附加表是否存在
     * @param string $table_name 附加表名
     * @author rocky <jy00730190@qq.com>
     * @return string
     */
    function table_exist($table_name = '')
    {
        return true == Db::query("SHOW TABLES LIKE '{$table_name}'");
    }
}

if (!function_exists('http_post')) {
    function http_post($url, $param, $post_file = false, $json = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        if (PHP_VERSION_ID >= 50500) {
            //curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, FALSE);
        }
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);

        if($json){
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($strPOST),
            ));
        }

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}

if (!function_exists('http_get')) {
    function http_get($url)
    {
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }
}

if (!function_exists('add_querystring_var')) {
    function add_querystring_var($url, $key, $value) {
        $url=preg_replace('/(.*)(?|&)'.$key.'=[^&]+?(&)(.*)/i','$1$2$4',$url.'&');
        $url=substr($url,0,-1);
        if(strpos($url,'?') === false){
            return ($url.'?'.$key.'='.$value);
        } else {
            return ($url.'&'.$key.'='.$value);
        }
    }
}

if (!function_exists('remove_xss')) {
    //使用htmlpurifier防范xss攻击
    function remove_xss($string){
        // 生成配置对象
        $cfg = HTMLPurifier_Config::createDefault();
        // 以下就是配置：
        $cfg -> set('Core.Encoding', 'UTF-8');
        // 设置允许使用的HTML标签
        $cfg -> set('HTML.Allowed','div,b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src]');
        // 设置允许出现的CSS样式属性
        $cfg -> set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
        // 设置a标签上是否允许使用target="_blank"
        $cfg -> set('HTML.TargetBlank', TRUE);
        // 使用配置生成过滤用的对象
        $obj = new HTMLPurifier($cfg);
        // 过滤字符串
        return $obj->purify($string);
    }
}

/**
 * 获取图片缩略图路径
 * @param int $id 附件id
 * @author rocky
 * @return string
 */
if (!function_exists('get_full_thumb')) {
    function get_full_thumb($id = 0)
    {
        $path = model('admin/attachment')->getThumbPath($id);
        if (!$path) {
            //$path = request()->domain().'/'.config('public_static_path').'admin/img/none.png';
            return;
        }

        return request()->domain().$path;
    }
}

/**
 * 获取图片缩略图路径
 * @param int $id 附件id
 * @author rocky
 * @return string
 */
if (!function_exists('get_thumbs')) {
    function get_thumbs($ids)
    {
        $paths = model('admin/attachment')->getThumbPaths($ids);
        foreach($paths as $k=>&$v){
            if (!$v) {
                //$v = request()->domain().'/'.config('public_static_path').'admin/img/none.png';
                $v = '';
            }else{
                if($v['thumb']){
                    $v = request()->domain().$v['thumb'];
                }else{
                    $v = request()->domain().$v['path'];
                }
            }
        }
        return $paths;
    }
}

if (!function_exists('get_full_file_path')) {
    /**
     * 获取附件路径
     * @param int $id 附件id
     * @author Rocky <310261067@qq.com>
     * @return string
     */
    function get_full_file_path($id = 0)
    {
        $path = model('admin/attachment')->getFilePath($id);
        if ($path) {
            if (strpos($path, 'http://') === false && strpos($path, 'https://') === false) {
                $path = request()->domain() . $path;
            }
        }else{
            $path = '';
        }

        return $path;
    }
}

if (!function_exists('get_full_files_path')) {
    /**
     * 批量获取附件路径
     * @param array $ids 附件id
     * @author Rocky <310261067@qq.com>
     * @return array
     */
    function get_full_files_path($ids = [])
    {
        $paths = model('admin/attachment')->getFilePath($ids);
        foreach($paths as $k=>&$path){
            if ($path) {
                if (strpos($path, 'http://') === false && strpos($path, 'https://') === false) {
                    $path = request()->domain() . '/' . $path;
                }
            }else{
                $path = '';
            }
        }

        return $paths;
    }
}

/**
 * 解析url中参数信息，返回参数数组
 */
if (!function_exists('convertUrlQuery')) {
    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
}

/**
 * 把数组拼接成url参数形式
 */
if (!function_exists('getUrlQuery')) {
    function getUrlQuery($array_query)
    {
        $tmp = array();
        foreach ($array_query as $k => $param) {
            $tmp[] = $k . '=' . $param;
        }
        $params = implode('&', $tmp);
        return $params;
    }
}

if (!function_exists('validate_idcard')) {
    function validate_idcard($idcard) {
        if(empty($idcard)){
            return false;
        }else{
            $idcard = strtoupper($idcard); # 如果是小写x,转化为大写X
            if(strlen($idcard) != 18 && strlen($idcard) != 15){
                return false;
            }
            # 如果是15位身份证，则转化为18位
            if(strlen($idcard) == 15){
                # 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
                if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
                    $idcard = substr($idcard, 0, 6) . '18' . substr($idcard, 6, 9);
                } else {
                    $idcard = substr($idcard, 0, 6) . '19' . substr($idcard, 6, 9);
                }
                # 加权因子
                $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                # 校验码对应值
                $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $checksum = 0;
                for ($i = 0; $i < strlen($idcard); $i++) {
                    $checksum += substr($idcard, $i, 1) * $factor[$i];
                }
                $idcard = $idcard . $code[$checksum % 11];
            }
            # 验证身份证开始
            $IDCardBody = substr($idcard, 0, 17); # 身份证主体
            $IDCardCode = strtoupper(substr($idcard, 17, 1)); # 身份证最后一位的验证码

            # 加权因子
            $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            # 校验码对应值
            $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $checksum = 0;
            for ($i = 0; $i < strlen($IDCardBody); $i++) {
                $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
            }
            $validateIdcard = $code[$checksum % 11];    # 判断身份证是否合理
            if($validateIdcard != $IDCardCode){
                return false;
            }else{
                return true;
            }
        }
    }
}

if (!function_exists('get_yesno')) {
    function get_yesno($key=false){
        $array = [1=>'是', 0=>'否'];

        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}

if (!function_exists('remove_xss')) {
    //使用htmlpurifier防范xss攻击
    function remove_xss($string){
        // 生成配置对象
        $cfg = HTMLPurifier_Config::createDefault();
        // 以下就是配置：
        $cfg -> set('Core.Encoding', 'UTF-8');
        // 设置允许使用的HTML标签
        //$cfg -> set('HTML.Allowed','div,b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src],hr');
        $cfg -> set('HTML.Allowed','div[style],b,strong,i,em,a[href|title],ul[style],ol,li[style],br,p[style],span[style],img[width|height|alt|src],hr,table[style|border|cellpadding|cellspacing],thead,tbody,tr,th,td[colspan|rowspan],h1,h2,h3,h4,h5,h6');
        // 设置允许出现的CSS样式属性
        $cfg -> set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align,text-indent');
        // 设置a标签上是否允许使用target="_blank"
        $cfg -> set('HTML.TargetBlank', TRUE);
        // 使用配置生成过滤用的对象
        $obj = new HTMLPurifier($cfg);
        // 过滤字符串
        return $obj->purify($string);
    }
}

if (!function_exists('get_area')) {
    function get_area($id){
        if(!$id) return;
        return db('common_area')->where('id', $id)->value('name');
    }
}

if (!function_exists('get_province')) {
    function get_province($key=false){
        $array = db('common_area')->where('level', 1)->column('id, name');
        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}

if (!function_exists('get_city')) {
    function get_city($pid=false, $key=false){
        if(!$pid){
            return;
        }

        $array = db('common_area')->where('level', 2)->where('pid', $pid)->column('id, name');

        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}

if (!function_exists('get_distinct')) {
    function get_distinct($pid=false, $key=false){
        if(!$pid){
            return;
        }

        $array = db('common_area')->where('level', 3)->where('pid', $pid)->column('id, name');
        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}

if (!function_exists('get_area')) {
    function get_area($id){
        if(!$id) return;
        return db('common_area')->where('id', $id)->value('name');
    }
}

if (!function_exists('get_province')) {
    function get_province($key=false){
        $array = db('common_area')->where('level', 1)->column('id, name');
        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}

if (!function_exists('get_city')) {
    function get_city($pid=false, $key=false){
        if(!$pid){
            return;
        }

        $array = db('common_area')->where('level', 2)->where('pid', $pid)->column('id, name');

        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}

if (!function_exists('get_distinct')) {
    function get_distinct($pid=false, $key=false){
        if(!$pid){
            return;
        }

        $array = db('common_area')->where('level', 3)->where('pid', $pid)->column('id, name');
        if($key === false){
            return $array;
        }else{
            if(isset($array[$key])){
                return $array[$key];
            }else{
                return;
            }
        }
    }
}